package ltesim.navigator;

import java.util.List;
import java.util.Vector;

import ltesim.natures.ProjectNature;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class ContentProvider implements ITreeContentProvider {

	@Override
	public void dispose() {
		System.out.println("ContentProvider.dispose"); 
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		System.out.println("ContentProvider.inputChanged: old: "
				+ oldInput.getClass().getName() + " new: "
				+ newInput.getClass().getName());
	}

	@Override
	public Object[] getElements(Object inputElement) {
		// TODO Auto-generated method stub
		return getChildren(inputElement);
	}

	private static final Object[] NO_CHILDREN = {};
	private LTESimProjectParent[] _LTESimProjectParent;

	@Override
	public Object[] getChildren(Object parentElement) {
		Object[] children = null;
		if (LTESimProjectWorkbenchRoot.class.isInstance(parentElement)) {
			if (_LTESimProjectParent == null) {
				_LTESimProjectParent = initializeParent(parentElement);
			}

			children = _LTESimProjectParent;
		} else {
			children = NO_CHILDREN;
		}

		return children;
	}

	private LTESimProjectParent[] initializeParent(Object parentElement) {
        IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

        List<LTESimProjectParent> list = new Vector<LTESimProjectParent>();
        for (int i = 0; i < projects.length; i++) {
            try {
                if (projects[i].getNature(ProjectNature.NATURE_ID) != null) {
                    list.add(new LTESimProjectParent(projects[i]));
                }
            } catch (CoreException e) {
                // Go to the next IProject
            }
        }

        LTESimProjectParent[] result = new LTESimProjectParent[list.size()];
        list.toArray(result);

        return result;
	}

	@Override
	public Object getParent(Object element) {
        System.out.println("ContentProvider.getParent: " + element.getClass().getName()); //$NON-NLS-1$

        return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		// TODO Auto-generated method stub
		return false;
	}

}
